import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class LocalStore {
  static final LocalStore _instance = LocalStore._internal();
  SharedPreferences? _prefs;

  factory LocalStore() {
    return _instance;
  }

  LocalStore._internal();

  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  /// 存储字符串
  Future<bool> setTextValue(String key, String value) async {
    if (_prefs == null) await init();
    return await _prefs!.setString(_generateKey(key), value);
  }

  /// 获取字符串
  String getTextValue(String key, {String defaultValue = ''}) {
    if (_prefs == null) return defaultValue;
    return _prefs!.getString(_generateKey(key)) ?? defaultValue;
  }

  /// 存储布尔值
  Future<bool> setFlagValue(String key, bool value) async {
    if (_prefs == null) await init();
    return await _prefs!.setBool(_generateKey(key), value);
  }

  /// 获取布尔值
  bool getFlagValue(String key, {bool defaultValue = false}) {
    if (_prefs == null) return defaultValue;
    return _prefs!.getBool(_generateKey(key)) ?? defaultValue;
  }

  /// 存储整数
  Future<bool> setNumberValue(String key, int value) async {
    if (_prefs == null) await init();
    return await _prefs!.setInt(_generateKey(key), value);
  }

  /// 获取整数
  int getNumberValue(String key, {int defaultValue = 0}) {
    if (_prefs == null) return defaultValue;
    return _prefs!.getInt(_generateKey(key)) ?? defaultValue;
  }

  /// 存储Map或自定义对象（转为JSON）
  Future<bool> setObjectValue(String key, Object value) async {
    if (_prefs == null) await init();
    String jsonString = jsonEncode(value);
    return await _prefs!.setString(_generateKey(key), jsonString);
  }

  /// 获取Map或自定义对象
  Map<String, dynamic>? getObjectValue(String key) {
    if (_prefs == null) return null;
    String? jsonString = _prefs!.getString(_generateKey(key));
    if (jsonString == null) return null;
    return jsonDecode(jsonString) as Map<String, dynamic>;
  }

  /// 移除指定键的数据
  Future<bool> removeValue(String key) async {
    if (_prefs == null) await init();
    return await _prefs!.remove(_generateKey(key));
  }

  /// 清空所有数据
  Future<bool> clearAll() async {
    if (_prefs == null) await init();
    return await _prefs!.clear();
  }

  /// 检查是否包含某个键
  bool containsKey(String key) {
    if (_prefs == null) return false;
    return _prefs!.containsKey(_generateKey(key));
  }

  /// 获取所有键
  Set<String> getAllKeys() {
    if (_prefs == null) return {};
    return _prefs!.getKeys();
  }

  String _generateKey(String key) {
    const String prefix = 'app_data_';
    return '$prefix$key';
  }
}
